import axios from "axios";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { RootState } from "../../store";
import {
  fetchErrorActionCreator,
  fetchStartActionCreator,
  fetchSuccessActionCreator,
} from "../../store/classify/classifyAction";
import "./style.css";

interface ListItemState {
  title: string;
  id: string;
  children: {
    title: string;
    url: string;
    desc: string;
    id: string;
  }[];
}

const Index: React.FC = () => {
  // const [loading, setLoading] = useState(true);
  // const [error, setError] = useState<null | string>(null);
  // const [list, setList] = useState<ListItemState[]>([]);
  const loading = useSelector((state: RootState) => state.classify.loading);
  const error = useSelector((state: RootState) => state.classify.error);
  const list = useSelector((state: RootState) => state.classify.list);
  const dispatch = useDispatch();
  const [activeIndex, setActiveIndex] = useState(0);

  const navigate = useNavigate();
  const fetchList = async () => {
    dispatch(fetchStartActionCreator());
    try {
      const resp = await axios.get("/api/list");
      // setList(resp.data.data);
      // setLoading(false);
      dispatch(fetchSuccessActionCreator(resp.data.data));
    } catch (e: any) {
      // setError(e.message);
      // setLoading(false);
      dispatch(fetchErrorActionCreator(e.message));
    }
  };

  useEffect(() => {
    fetchList();
  }, []);

  if (loading) {
    return <div>数据加载中...</div>;
  }
  if (error) {
    return <div>网站请求失败， 点击重新请求--{error}</div>;
  }

  return (
    <div className="tab">
      <div className="left">
        {list.map((v, i) => {
          return (
            <span
              key={v.id}
              className={activeIndex === i ? "active" : ""}
              onClick={() => setActiveIndex(i)}
            >
              {v.title}
            </span>
          );
        })}
      </div>
      <div className="right">
        {list[activeIndex].children.map((v) => {
          return (
            <dl key={v.id} onClick={() => navigate("/detail/" + v.id)}>
              <dt>
                <img src={v.url} alt="" />
              </dt>
              <dd>
                <h3>{v.title}</h3>
                <p>{v.desc}</p>
              </dd>
            </dl>
          );
        })}
      </div>
    </div>
  );
};

export default Index;
